﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Data;
using System.Xml;
using System.Windows.Forms;
using System.IO;
using System.Configuration;

namespace AnyOffice.SmsGateWay
{
    public class SmsGateWay : NoteGateWay.NoteGateWay
    {

        /// <summary>
        /// 短信猫端口号
        /// </summary>
        private static uint modPort = 5;

        /// <summary>
        /// 获取短信类型：0：未读短信；1：已读短信；2：待发短信；3：已发短信；4：全部短信
        /// </summary>
        private static string receiveType = string.Empty;

        /// <summary>
        /// 1表示是否删除指定短信
        /// </summary>
        private static string isDelmsg = "1";

        private void AddDt(DataTable dt, long sequence, int intNum, string strContent, string strMobile, string strCpn, string strType)
        {
            DataRow row = dt.NewRow();
            row["sequence"] = sequence;
            row["Num"] = intNum;
            row["Content"] = strContent;
            row["Mobile"] = strMobile;
            row["Cpn"] = strCpn;
            row["Type"] = strType;
            dt.Rows.Add(row);
        }

        private string GetXmlNodeValue(string strNodeValue)
        {
            XmlDocument document = new XmlDocument();
            string filename = "NoteParmValue.xml";
            document.Load(Application.StartupPath + "\\" + filename);
            return document.SelectSingleNode("Parms/SmsSetting/" + strNodeValue).InnerText.ToString();
        }

        public override object Login()
        {
            try
            {
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "开始读取xml中配置的modPort,receiveType,isDelmsg");

                modPort = Convert.ToUInt16(this.GetXmlNodeValue("modPort"));
                receiveType = this.GetXmlNodeValue("receiveType");
                isDelmsg = this.GetXmlNodeValue("deleteFlag");

                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "modPort=" + modPort + ",receiveType=" + receiveType + ",isDelmsg=" + isDelmsg);

                String TypeStr = "";
                String CopyRightToCOM = "";
                String CopyRightStr = "//上海迅赛信息技术有限公司,网址www.xunsai.com//";

                if (Sms_Connection(CopyRightStr, modPort, 9600, out TypeStr, out CopyRightToCOM) == 1) ///5为串口号，0为红外接口，1,2,3,...为串口
                {
                    WriteLogFile(DateTime.Now.ToString("d") + ".txt", "登陆失败，问题可能是端口号配置错误！");
                    return 1;
                }
            }
            catch (Exception exception)
            {
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "登陆失败，问题可能是：" + exception.Message);
                return 3;
            }

            return 0;
        }

        public override object Logout()
        {
            object obj2;
            try
            {
                Sms_Disconnection();
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "退出成功!");
                obj2 = 1;
            }
            catch (Exception exception)
            {
                obj2 = 0;
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "退出失败，问题可能是：" + exception.Message);
            }
            return obj2;
        }

        private DataTable NewDt()
        {
            DataTable table = new DataTable();
            table.Columns.Add("sequence", typeof(long));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("Content", typeof(string));
            table.Columns.Add("Mobile", typeof(string));
            table.Columns.Add("Cpn", typeof(string));
            table.Columns.Add("Type", typeof(string));
            return table;
        }

        public override DataSet Receive()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("seq", typeof(long));
            dt.Columns.Add("mid", typeof(string));
            dt.Columns.Add("con", typeof(string));
            dt.Columns.Add("lid", typeof(string));
            dt.Columns.Add("tim", typeof(string));

            try
            {
                String ReceiveSmsStr = "";

                if (Sms_Receive(receiveType, out ReceiveSmsStr) == 1)
                {
                    if (!String.IsNullOrEmpty(ReceiveSmsStr))
                    {
                        string[] strmsg = ReceiveSmsStr.Split(new char[] { '|' });
                        for (int i = 1; i < strmsg.Length; i++)
                        {
                            string[] strsin = strmsg[i].Split(new char[] { '#' });
                            DataRow dr = dt.NewRow();
                            dr["ID"] = strsin[0].ToString();
                            dr["Type"] = strsin[1].ToString();
                            dr["PhoneNum"] = strsin[2].ToString();
                            dr["Content"] = strsin[3].ToString();
                            dr["Time"] = strsin[4].ToString();
                            dt.Rows.Add(dr);

                            //如果删除
                            if (isDelmsg.Equals("1"))
                            {
                                Sms_Delete(strsin[0].ToString());
                            }

                            WriteLogFile(DateTime.Now.ToString("d") + ".txt", "接收短信成功!\r\n");
                            WriteLogFile(DateTime.Now.ToString("d") + ".txt", string.Format("SourceAddr ={0},Content={1},RecvTime={2}", new object[] { dr["PhoneNum"].ToString(), dr["Content"].ToString(), dr["Time"].ToString() }));
                        }
                    }
                }
                else
                {
                    WriteLogFile(DateTime.Now.ToString("d") + ".txt", "没有接收到短信");                    
                }
            }
            catch(Exception ex)
            {
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "接收短信失败，错误的原因可能是：" + ex.Message.ToString());
            }
            DataSet set = new DataSet();
            set.Tables.Add(dt);
            return set;
        }

        public override DataTable Send(DataSet ds)
        {
            DataTable dt = this.NewDt();
            if (((ds != null) && (ds.Tables.Count > 0)) && (ds.Tables[0].Rows.Count > 0))
            {
                //读取xml配置参数
                modPort = Convert.ToUInt16(this.GetXmlNodeValue("modPort"));
                receiveType = this.GetXmlNodeValue("receiveType");
                isDelmsg = this.GetXmlNodeValue("deleteFlag");

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    try
                    {
                        string content = row["Content"].ToString();
                        string strCpn = row["Cpn"].ToString();
                        string strType = row["Type"].ToString();
                        string[] strArray = row["Mobile"].ToString().Split(new char[] { ',' });

                        for (int i = 0; i < strArray.Length; i++)
                        {
                            string destAddr = strArray[i].ToString();
                            int intNum = sendSms(modPort, content, strArray[i].ToLower());
                            WriteLogFile(DateTime.Now.ToString("d") + ".txt", "发送短信:" + content + "到" + strArray[i].ToLower());
                            if (intNum == 1)
                            {
                                this.AddDt(dt, 0L, Convert.ToInt16(intNum), content, destAddr, strCpn, strType);
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        WriteLogFile(DateTime.Now.ToString("d") + ".txt", "发送短信时发生异常，系统将继续发送后面的短信，错误的原因是：" + ex.Message.ToString());                        
                    }
                }
            }
            return dt;
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="modPort">COM端口号</param>
        /// <param name="mes">信息内容</param>
        /// <param name="phoneNum">手机号码</param>
        /// <returns>0，无法连接短信猫，1发送成功，2发送不成功</returns>
        public int sendSms(uint modPort, string mes, string phoneNum)
        {
            try
            {
                if (Sms_ConnectionCheck(modPort))
                {
                    uint i = Sms_Send(phoneNum, mes);
                    if (i == 1)
                    {
                        return 1;
                    }
                    else
                    {
                        return 2;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                WriteLogFile(DateTime.Now.ToString("d") + ".txt", "发送短信:" + mes + "到" + phoneNum + "时发生异常：" + ex.Message.ToString());
                return 0;
            }
            finally
            {

                Sms_Disconnection();
            }
        }

        public bool Sms_ConnectionCheck(uint ModPort)
        {
            String TypeStr = "";
            String CopyRightToCOM = "";
            String CopyRightStr = "//上海迅赛信息技术有限公司,网址www.xunsai.com//";

            if (Sms_Connection(CopyRightStr, ModPort, 9600, out TypeStr, out CopyRightToCOM) == 1) ///5为串口号，0为红外接口，1,2,3,...为串口
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strConn"></param>
        /// <returns></returns>
        public override DataTable Send(string strConn)
        {
            DataTable dt = this.NewDt();
            string[] strArray = strConn.Split(new char[] { ':' });
            string[] strArray2 = strArray[0].Split(new char[] { ',' });
            string content = strArray[1].ToString();
            string strCpn = strArray[2].ToString();
            string strType = strArray[3].ToString();
            for (int i = 0; i < strArray2.Length; i++)
            {
                modPort = Convert.ToUInt16(this.GetXmlNodeValue("modPort"));
                receiveType = this.GetXmlNodeValue("receiveType");
                isDelmsg = this.GetXmlNodeValue("deleteFlag");

                string destAddr = strArray2[i].ToString();
                int intNum = sendSms(modPort, content, strArray[i].ToLower());

                if (intNum == 1)
                {
                    this.AddDt(dt, 0L, Convert.ToInt16(intNum), content, destAddr, strCpn, strType);
                }
            }
            return dt;
        }

        #region 打日志

        /// <summary>
        /// 向文件中写入文本
        /// </summary>
        /// <param name="Directory">文件夹名称，要求以"\\"结尾</param>
        /// <param name="strLogFileName">文件名</param>
        /// <param name="strLog">文本内容</param>
        /// <returns>写入成功或否</returns>
        public static bool WriteLogFile(string strLogFileName, string strLog)
        {
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["WriteLog"].ToString()))
            {
                if (Convert.ToInt16(ConfigurationManager.AppSettings["LogType"].ToString())== 1)
                {
                    string strPath = Application.StartupPath + "\\AppLog\\";

                    strPath = strPath + strLogFileName;

                    try
                    {
                        System.IO.StreamWriter objSw = new StreamWriter(strPath, true);
                        objSw.WriteLine(DateTime.Now.ToString());
                        objSw.WriteLine("---------------------------------");
                        objSw.WriteLine(strLog);
                        objSw.WriteLine("---------------------------------------------------------------------------------------------------");
                        objSw.WriteLine(" ");
                        objSw.Flush();
                        objSw.Close();
                        return true;
                    }
                    catch
                    {
                        //WorkEventLogger.WriteInformation("输出日志时发生异常，日志文件地址是：" + strPath);
                        return false;
                    }
                }
                else
                {
                    WorkEventLogger.WriteInformation(strLog);
                }
            }

            return true;
        }

        #endregion

        #region DllImport

        [STAThread]

        [DllImport("sms.dll", EntryPoint = "Sms_Connection")]
        public static extern uint Sms_Connection(string CopyRight, uint Com_Port, uint Com_BaudRate, out string Mobile_Type, out string CopyRightToCOM);

        [DllImport("sms.dll", EntryPoint = "Sms_Disconnection")]
        public static extern uint Sms_Disconnection();

        [DllImport("sms.dll", EntryPoint = "Sms_Send")]
        public static extern uint Sms_Send(string Sms_TelNum, string Sms_Text);

        [DllImport("sms.dll", EntryPoint = "Sms_Receive")]
        public static extern uint Sms_Receive(string Sms_Type, out string Sms_Text);

        [DllImport("sms.dll", EntryPoint = "Sms_Delete")]
        public static extern uint Sms_Delete(string Sms_Index);

        [DllImport("sms.dll", EntryPoint = "Sms_AutoFlag")]
        public static extern uint Sms_AutoFlag();

        [DllImport("sms.dll", EntryPoint = "Sms_NewFlag")]
        public static extern uint Sms_NewFlag();

        #endregion
    }
}
